package com.qianya.oa.controller.activiti;

import com.qianya.oa.common.core.controller.BaseController;
import com.qianya.oa.common.core.domain.entity.SysUser;
import com.qianya.oa.common.core.page.TableDataInfo;
import com.qianya.oa.common.utils.StringUtils;
import com.qianya.oa.domain.FlowInfo;
import com.qianya.oa.domain.TaskInfo;
import com.qianya.oa.dto.FlowHistoryQueryParam;
import com.qianya.oa.util.CommonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricProcessInstanceQuery;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Api(value = "待办任务接口")
@Controller
@RequestMapping("/completedTask/manage")
public class CompletedTaskController extends BaseController {

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private TaskService taskService;

    @Resource
    private FormService formService;

    @Resource
    private HistoryService historyService;

    @Resource
    RepositoryService repositoryService;

    private String prefix = "activiti/task";


    @GetMapping("/mytask")
    public String mytasks() {
        return prefix + "/mytasks";
    }

    @GetMapping("/alltasks")
    public String alltasks() {
        return prefix + "/alltasks";
    }

    /**
     * 查询我的已办任务列表
     *
     * @return
     */
    @ApiOperation("查询我的已办任务列表")
    @PostMapping("/myDoneList")
    @ResponseBody
    public CommonResult<TableDataInfo> myDoneList(@RequestBody TaskInfo param) {
        SysUser user = getSysUser();
        String username = user.getLoginName();
        int start = (param.getPageNum() - 1) * param.getPageSize();
        Integer pageSize = param.getPageSize();
        HistoricProcessInstanceQuery condition = historyService.createHistoricProcessInstanceQuery();
        if (StringUtils.isNotEmpty(param.getProcessName())) {
            condition.processDefinitionName(param.getProcessName());
        }
        condition.involvedUser(username);
//        if (StringUtils.isNotBlank(param.getName())) {
//            condition.processInstanceNameLike("%" + taskListQo.getName() + "%");
//        }
//        if (param.getCategoryId() != null) {
//            condition.processDefinitionCategory(String.valueOf(param.getCategoryId()));
//        }

        //查询关于我的所有流程
        int total = condition.orderByProcessInstanceStartTime().desc().list().size();
        List<HistoricProcessInstance> processList = condition.orderByProcessInstanceStartTime().desc().listPage(start, pageSize);
        List<FlowInfo> flows = new ArrayList<>();
        processList.stream().forEach(p -> {
            FlowInfo info = new FlowInfo();
            info.setProcessInstanceId(p.getId());
            info.setBusinessKey(p.getBusinessKey());
            info.setName(p.getProcessDefinitionName());
            info.setStartTime(p.getStartTime());
            info.setEndTime(p.getEndTime());
            info.setStartUserId(p.getStartUserId());
            if (p.getEndTime() == null) {
                info.setEnded(false);
                // 查看当前活动任务
                List<Task> tasks = taskService.createTaskQuery().processInstanceId(p.getId()).list();
                if (tasks.size() > 0) {
                    String taskName = "";
                    String assignee = "";
                    for (Task t : tasks) {
                        taskName += t.getName() + ",";
                        assignee += t.getAssignee() + ",";

                        String taskId = t.getId();
                        String formKey = formService.getTaskFormData(taskId).getFormKey();
                        info.setCurrentFormKey(formKey);
                    }
                    taskName = taskName.substring(0, taskName.length() - 1);
                    assignee = assignee.substring(0, assignee.length() - 1);
                    info.setCurrentTask(taskName);
                    info.setAssignee(assignee);
                }
            } else {
                info.setEnded(true);
            }
            flows.add(info);
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(flows);
        rspData.setTotal(total);
        return CommonResult.success(rspData);
    }

    @ApiOperation("查询一个流程的活动历史")
    @RequestMapping(value = "/flow/history", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<TableDataInfo> history(@RequestBody FlowHistoryQueryParam param) {
        String processInstanceId = param.getProcessInstanceId();
        Integer pageNum = param.getPageNum();
        Integer pageSize = param.getPageSize();
        int start = (pageNum - 1) * pageSize;
        List<HistoricActivityInstance> history = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).activityType("userTask").orderByHistoricActivityInstanceStartTime().asc().listPage(start, pageSize);
        int total = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).activityType("userTask").orderByHistoricActivityInstanceStartTime().asc().list().size();
        List<TaskInfo> infos = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        history.stream().forEach(h -> {
            TaskInfo info = new TaskInfo();
            info.setProcessInstanceId(h.getProcessInstanceId());
            info.setStartTime(sdf.format(h.getStartTime()));
            if (h.getEndTime() != null) {
                info.setEndTime(sdf.format(h.getEndTime()));
            }
            info.setAssignee(h.getAssignee());
            info.setTaskName(h.getActivityName());
            List<Comment> comments = taskService.getTaskComments(h.getTaskId());
            if (comments.size() > 0) {
                info.setComment(comments.get(0).getFullMessage());
            }
            //info.setFormKey();
            infos.add(info);
        });
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(infos);
        rspData.setTotal(total);
        return CommonResult.success(rspData);
    }

}

